// 作者:wisher
// 时间:2023/6/25
// 说明:APP手机号登录处理

const db = uniCloud.database();
randomNum = function(min = 0, max = 10) {
	return Math.round(Math.random() * (max - min)) + min;
}
randomName = () => {
	let a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
	return a[randomNum(0, 9)] + a[randomNum(0, 9)] + a[randomNum(0, 9)] + (randomNum(0, 9)) +
		(randomNum(0, 9)) + (randomNum(0, 9)) + (randomNum(0, 9)) + (randomNum(0,
			9))
}
randomAvatarUrl = () => {
	let a = ['https://tse3-mm.cn.bing.net/th/id/OIP-C.XpnLCXvNjh1PjkvAr-t6nAAAAA?w=210&h=210&c=7&r=0&o=5&pid=1.7',
		'https://tse3-mm.cn.bing.net/th/id/OIP-C.id3YItDsqVwBIiohmCogSgAAAA?w=210&h=210&c=7&r=0&o=5&pid=1.7',
		'https://tse2-mm.cn.bing.net/th/id/OIP-C.FWDygLJAzn-CRnX1xX30zwAAAA?w=210&h=210&c=7&r=0&o=5&pid=1.7',
		`https://tupian.qqw21.com/article/UploadPic/2020-5/202052623103460996.jpg`,
		'https://tupian.qqw21.com/article/UploadPic/2020-9/20209172232571440.jpg',
		'https://p.qqan.com/up/2021-6/2021612102682393.png',
		'https://tupian.qqw21.com/article/UploadPic/2020-7/202071322312980333.jpg',
		'https://p.qqan.com/up/2021-3/2021351114587563.jpg',
		'https://ts1.cn.mm.bing.net/th/id/R-C.e3050cfcfcf639f1730328457fce750f?rik=QlcndX%2bLSXM3NA&riu=http%3a%2f%2fwww.gx8899.com%2fuploads%2fallimg%2f2018030309%2fig53h33pmzi.jpg&ehk=oSWS%2fnSQTZOz0LlTTDJnXgE9eUuQU4trI74taTbzz3A%3d&risl=&pid=ImgRaw&r=0',
		'https://p.qqan.com/up/2021-4/16184547854968092.jpg'
	]
	return a[randomNum(0, 9)]
}
exports.main = async (event, context) => {
	// event里包含着客户端提交的参数
	const res = await uniCloud.getPhoneNumber({
		appid: '__UNI__EE9AB59', // 替换成自己开通一键登录的应用的DCloud appid
		provider: 'univerify',
		apiKey: '46054ab356b0d878995f5bdc6709ab2c', // 在开发者中心开通服务并获取apiKey
		apiSecret: '4f590f669338d00cba91141d253601f0', // 在开发者中心开通服务并获取apiSecret
		access_token: event.access_token,
		openid: event.openid
	})
	// let res = {
	// 	"code": 0,
	// 	"success": true,
	// 	"phoneNumber": "18552145532"
	// }

	const collection = db.collection('users');
	let user = (await collection.where({
		phoneNumber: res.phoneNumber
	}).get()).data
	let ret = user
	if (user.length == 0) {
		//账号不存在
		ret = (await collection.doc((await collection.add({
			username: randomName(),
			phoneNumber: res.phoneNumber,
			regtime: new Date().getTime(),
			openid: 0,
			avatarUrl: randomAvatarUrl()
		})).id).get()).data
	}

	return {
		code: 0,
		data: ret[0]
	}
};